import cv2
import numpy as np
import utlis

def imshow(name,img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Video_Show = True
path_img = "C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\zfb.jpg"
cap = cv2.VideoCapture(0)
cap.set(10, 160)
height_img = 640
width_img = 480

# utlis.initializeTrackbars()
count = 0


while True:
    frameBlank = np.zeros((height_img, width_img, 3), np.uint8)
    if Video_Show:
        ret, frame = cap.read()
    else:
        frame = cv2.imread(path_img)

    frame = cv2.resize(frame, (width_img, height_img))
    # 灰度化
    frameGary = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 高斯模糊
    frameBlur = cv2.GaussianBlur(frameGary, (5, 5), 1)
    # 获取滑动条的值
    # thres = utlis.valTrackbars()
    # 寻找边缘
    frameCanny = cv2.Canny(frameBlur, 50,50)
    kernel = np.ones((5,5))
    # 膨胀
    frameDial = cv2.dilate(frameCanny, kernel=kernel, iterations=2)
    # 腐蚀
    frameEro = cv2.erode(frameDial, kernel=kernel, iterations=1)

    frameContours =frame.copy()
    frameBigContours = frame.copy()
    # 获取轮廓
    contours,hierarchy = cv2.findContours(frameEro, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 画出轮廓
    cv2.drawContours(frameContours, contours, -1,(0,255,0),3)
    # imshow("frameContours",frameContours)


    # 获取最大轮廓
    biggest,maxArea = utlis.biggestContour(contours)
    if biggest.size != 0:
        biggest = utlis.reorder(biggest)
        cv2.drawContours(frameBigContours,biggest,-1,(0,255,0),2)
        # 画出矩形
        frameBigContours = utlis.drawRectangle(frameBigContours,biggest, 2)
        pts1 = np.float32(biggest)
        # 获取变换矩阵
        pts2 = np.float32([[0,0],[width_img,0],[0,height_img],[width_img,height_img]])
        # 透视变换(将倾斜图片变正)
        matrix = cv2.getPerspectiveTransform(pts1,pts2)
        dst = cv2.warpPerspective(frame,matrix,(width_img,height_img))
        # 截取
        dst = dst[20:dst.shape[0]-20,20:dst.shape[1]-20]
        # 设置大小
        dst = cv2.resize(dst,(width_img,height_img))

        # 灰度化
        dstGary = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
        # 自适应二值化
        dstAdaptiveThre = cv2.adaptiveThreshold(dstGary,255,1,1,7,2)
        # 反转
        dstAdaptiveThre = cv2.bitwise_not(dstAdaptiveThre)
        # 中值滤波,处理胡椒噪点
        dstAdaptiveThre = cv2.medianBlur(dstAdaptiveThre,3)
        # 显示
        imageArray = ([frame,frameGary,frameCanny,frameContours],
                      [frameBigContours,dst,dstGary,dstAdaptiveThre])


    else:
        imageArray = ([frame,frameGary,frameCanny,frameContours],
                      [frameBlank,frameBlank,frameBlank,frameBlank])

    lables = [["Original", "Gray", "Threshold", "Contours"],
              ["frameBigContours", "dst", "dstGary", "dstAdaptiveThre"]]
    # lables = [str(label) for label in lables]
    stackedImage = utlis.stackImages(imageArray, 0.75)
    cv2.imshow("Result", stackedImage)

    # 保存
    if cv2.waitKey(1) & 0xFF == ord('s'):
        cv2.imwrite("./"+str(count)+".jpg",dst)
        cv2.rectangle(stackedImage, ((int(stackedImage.shape[1] / 2) - 230), int(stackedImage.shape[0] / 2) + 50),
                      (1100, 350), (0, 255, 0), cv2.FILLED)
        cv2.putText(stackedImage, "Scan Saved", (int(stackedImage.shape[1] / 2) - 20, int(stackedImage.shape[0] / 2)),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
        cv2.imshow('Result', stackedImage)
        cv2.waitKey(300)
        count += 1






